<?php

use app\model\AccountManage;
use app\model\Company;
use app\model\PartnerUser;


function GetRandStr($length)
{
    //字符组合
    $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $len = strlen($str) - 1;
    $randstr = '';
    for ($i = 0; $i < $length; $i++) {
        $num = mt_rand(0, $len);
        $randstr .= $str[$num];
    }
    return $randstr;
}


function GetRandInt($length)
{
    //字符组合
    $str = '0123456789';
    $len = strlen($str) - 1;
    $randstr = '';
    for ($i = 0; $i < $length; $i++) {
        $num = mt_rand(0, $len);
        $randstr .= $str[$num];
    }
    return $randstr;
}


function returnSuccess($code = 200, $msg = '请求成功', $data = '')
{
    echo json_encode([
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ], JSON_UNESCAPED_UNICODE);
    exit();
}

function returnFail($code, $msg = '', $data = '')
{
    echo json_encode([
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ], JSON_UNESCAPED_UNICODE);
    exit();
}


function geterateToken()
{
    $str = md5(uniqid(md5(microtime(true)), true));
    $token = sha1($str . "bx89qkZ9DC7EZ5qv");
    return $token;
}

//function linkRedis($db=0){
//    $redis = new \Redis();
//    $redis->connect("r-m5e2r376ph5v3ecz0cpd.redis.rds.aliyuncs.com","6379");
//    $redis->auth("xingkong:QbIZvdt9YGkSiSu7");
//    $redis->select($db);
//    return $redis;
//}

function linkRedis($db=0){
    $redis = new \Redis();
    $redis->connect("127.0.0.1","6379");
    $redis->auth(\think\facade\Env::get('redis.auth','QbIZvdt9YGkSiSu7'));
    $redis->select($db);
    return $redis;
}



function ipSendLimit($redis, $mobile)
{
    $mobileStr = "sendCount_" . $mobile;

    $mobileCount = $redis->get($mobileStr);
    date_default_timezone_set("PRC");
    $start_time = strtotime(date("Y-m-d", time()));
    $end_time = $start_time + 60 * 60 * 24;
    if (empty($mobileCount)) {
        $redis->set($mobileStr, 1, $end_time - time());
    } else {
        $redis->set($mobileStr, $mobileCount + 1, $end_time - time());
    }
    if ($mobileCount > 10) {
        echo json_encode(array('status' => 1001, 'msg' => '当前手机号发送超过限制'));
        exit;
    }
}


/**
 * http get 请求
 *
 * @param string $url 请求地址
 * @param array $header 请求头部
 *
 * @return array
 */
function http_get($url, $header = [])
{
    if (empty($header)) {
        $header = [
            "Content-type:application/json;",
            "Accept:application/json"
        ];
    }

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    $response = curl_exec($curl);
    curl_close($curl);
    $response = json_decode($response, true);

    return $response;
}

/**
 * http post 请求
 *
 * @param string $url 请求地址
 * @param array $param 请求参数
 * @param array $header 请求头部
 *
 * @return array
 */
function http_post($url, $param = [], $header = [])
{
    $param = json_encode($param);

    if (empty($header)) {
        $header = [
            "Content-type:application/json;charset='utf-8'",
            "Accept:application/json"
        ];
    }

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($curl);
    curl_close($curl);
    $response = json_decode($response, true);

    return $response;
}


/**
 * http post 请求
 *
 * @param string $url 请求地址
 * @param array $param 请求参数
 * @param array $header 请求头部
 *
 * @return array
 */
function http_post2($url, $param = [], $header = [])
{
//    $param = json_encode($param);

    if (empty($header)) {
        $header = [
            "Content-type:application/x-www-form-urlencoded",
//            "Accept:application/json"
        ];
    }

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($param));
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($curl);
    curl_close($curl);
    $response = json_decode($response, true);

    return $response;
}


function curlRequest($url, $data = '')
{
    $ch = curl_init();
    $params[CURLOPT_URL] = $url;    //请求url地址
    $params[CURLOPT_HEADER] = false; //是否返回响应头信息
    $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
    $params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
    $params[CURLOPT_TIMEOUT] = 30; //超时时间
    if (!empty($data)) {
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_POSTFIELDS] = $data;
    }
    $params[CURLOPT_SSL_VERIFYPEER] = false;//请求https时设置,还有其他解决方案
    $params[CURLOPT_SSL_VERIFYHOST] = false;//请求https时,其他方案查看其他博文
    curl_setopt_array($ch, $params); //传入curl参数
    $content = curl_exec($ch); //执行
    curl_close($ch); //关闭连接
    return $content;
}


function https_request_one($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 1 是post 2是get

    $output = curl_exec($curl);

    curl_close($curl);
    return $output;
}

/**
 * 距离当天结束时间的数据
 * @return false|float|int
 */
function getEndTime()
{
    $start_time = strtotime(date("Y-m-d", time()));
    //当天结束之间  $endtime=getEndTime();
    return $start_time + 60 * 60 * 24 - time() - 5;

}

/**
 * 用户id获取,公司id获取
 *
 * @return int
 */
function get_company_id($uid, $type=1): int
{
    $res = \app\service\MemberService::getCompanyIdByUid($uid, $type);
    return $res['company_id'];
}

/**
 * 用户id获取,合作商id获取
 *
 * @return int
 */
function get_partner_id($uid = 0): int
{
    $res = \app\service\MemberService::getPartnerIdByUid($uid);
    return $res['partner_id'];
}

function get_partner_ids($uid = 0)
{
    $res = \app\service\MemberService::getPartnerIdByUid($uid);
    return $res;
}

/**
 * 根据手机号获取
 *
 * @return int
 */
function get_partner_info($data)
{
    return \app\model\PartnerUserModel::find_user($data);
}

function get_partner_info2($data, $id)
{
    return \app\model\PartnerUserModel::find_user2($data, $id);
}


function getNowMonth()
{
    $firstDay = date('Y-m-01', time());

    $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
    return [
        'firstDay' => $firstDay,
        'lastDay' => $lastDay
    ];
}

function getAppointMonth($time)
{
    $firstDay = date('Y-m-01', $time);

    $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
    return [
        'firstDay' => $firstDay,
        'lastDay' => $lastDay
    ];
}

function getScopeView($userId)
{
    $redis = linkRedis(5);
    $userIds = $redis->get('scope_view' . $userId);
    if (!empty($userIds)) {
        return json_decode($userIds, true);
    } else {
        return 0;
    }
}

/**
 * 获取当前月的所有日期
 * @return array
 */
function getMonthDays()
{
    $monthDays = [];
    $firstDay = date('Y-m-01', time());
    $i = 0;
    $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
    while (date('Y-m-d', strtotime("$firstDay +$i days")) <= $lastDay) {
        $monthDays[] = date('Y-m-d', strtotime("$firstDay +$i days"));
        $i++;
    }
    return $monthDays;
}


/**
 * 获取月份的开始和结束日期
 *
 * @param string $month 月份
 *
 * @return array
 */
function monthStartEnd($month = '')
{
    if (empty($month)) {
        $month = date('Y-m');
    }

    $sta = $month . '-01';
    $t = date('t', strtotime($sta));
    $end = $month . '-' . $t;
    $date[] = $sta;
    $date[] = $end;

    return $date;
}


/**
 * 获取当前时间
 */

function getNowDateTime()
{
    return date('Y-m-d H:i:s', time());
}

//经度正则
function LonGrep($content): bool
{
    $format = '/^[\-\+]?(0(\.\d{1,10})?|([1-9](\d)?)(\.\d{1,10})?|1[0-7]\d{1}(\.\d{1,10})?|180\.0{1,10})$/';
    if (preg_match($format, $content)) {
        return true;
    } else {
        return true;
    }
}

//纬度正则
function LatGrep($content): bool
{
    $format = '/^[\-\+]?((0|([1-8]\d?))(\.\d{1,10})?|90(\.0{1,10})?)$/';
    if (preg_match($format, $content)) {
        return true;
    } else {
        return true;
    }
}


/**
 * 计算两组经纬度坐标 之间的距离
 * params ：lat1 纬度1； lng1 经度1； lat2 纬度2； lng2 经度2； len_type （1:m or 2:km);
 * return m or km
 */
function GetDistance($lat1, $lng1, $lat2, $lng2, $decimal = 2)
{
    $EARTH_RADIUS = 6378.137;
    $PI = 3.1415926;
    $radLat1 = $lat1 * $PI / 180.0;
    $radLat2 = $lat2 * $PI / 180.0;
    $a = $radLat1 - $radLat2;
    $b = ($lng1 * $PI / 180.0) - ($lng2 * $PI / 180.0);
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * $EARTH_RADIUS;
    $s = round($s * 1000);
    $line = round($s, $decimal);
    return $line;
}

function get_distance($from, $to, $km = true, $decimal = 2)
{
    sort($from);
    sort($to);
    $EARTH_RADIUS = 6370.996; // 地球半径系数

    $distance = $EARTH_RADIUS * 2 * asin(sqrt(pow(sin(($from[0] * pi() / 180 - $to[0] * pi() / 180) / 2), 2) + cos($from[0] * pi() / 180) * cos($to[0] * pi() / 180) * pow(sin(($from[1] * pi() / 180 - $to[1] * pi() / 180) / 2), 2))) * 1000;

    if ($km) {
        $distance = $distance / 1000;
    }

    return round($distance, $decimal);
}


function getdistances($lng1, $lat1, $lng2, $lat2)//根据经纬度计算距离
{
//将角度转为狐度 
    $radLat1 = deg2rad($lat1);
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;//两纬度之差,纬度<90
    $b = $radLng1 - $radLng2;//两经度之差纬度<180
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;
    return $s;
}

function getTodayDate()
{
    return date('Y-m-d', time());
}

function getDay()
{
    return date('yymd', time());
}

function baidutogps($longitude, $dimension)
{
    $url = "https://api.map.baidu.com/geoconv/v1/?coords=" . $longitude . "," . $dimension . "&from=5&to=3&ak=70TtqrtQyAsWkGMUCItMx3cOFXbDXDdh";
    $httpres = http_get($url);
    if ($httpres['status'] == 0) {
        return $httpres['result'];
    } else {
        return 400;
    }
}

function diffTime($startTime, $endTime)
{
    $date = floor((strtotime($endTime) - strtotime($startTime)) / 86400);
    $hour = floor((strtotime($endTime) - strtotime($startTime)) / 86400 / 3600);
    $minute = floor((strtotime($endTime) - strtotime($startTime)) / 86400 / 60);
    $second = floor((strtotime($endTime) - strtotime($startTime)) / 86400 / 60);
    return $hour . '小时' . $minute . '分钟';
}

function timediff($begin_time, $end_time)
{
    $begin_time = strtotime($begin_time);
    $end_time = strtotime($end_time);

    if ($begin_time < $end_time) {
        $starttime = $begin_time;
        $endtime = $end_time;
    } else {
        $starttime = $end_time;
        $endtime = $begin_time;
    }
    $timediff = $endtime - $starttime;
    $days = intval($timediff / 86400);
    $remain = $timediff % 86400;
    $hours = intval($remain / 3600);
    $remain = $remain % 3600;
    $mins = intval($remain / 60);
    $secs = $remain % 60;
    $res = $hours . '小时' . $mins . '分钟';
    return $res;
}

function getNo($prefix)
{
    #date 数据可以按照自己方式设置
    return $prefix . date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

/**
 *  获取uid 数据权限
 * @param $id
 * @param $companyId
 * @param $departmentId
 * @return string
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function getUid($id,$companyId = '',$departmentId = ''){

    $partnerUserModel = PartnerUser::with(['role'])->where('id',request()->param('uid'))->find();
    $uid = $partnerUserModel->source.'-'.$id;
    if($partnerUserModel->role->id == 1){//超级管理员
        //获取集团id
        $uid = '1';
        $group = Company::where('id',$companyId)->value('group_id');
        $uid .= '-'.$group;
        if($companyId)   $uid .=  '-'.$companyId;
        if($departmentId)   $uid .=  '-'.$departmentId;
        $uid .= '-'.$id;
    }
    return $uid;
}